﻿using System;
using System.Configuration;
using System.Timers;
using System.Net;
using System.Diagnostics;

namespace WarmUpService
{
	public class TargetOperate
	{
		string sourceName = "WarmUpServiceSource";
		string logName = "WarmUpServiceLog";

		/// <summary>
		/// Get configuration details from app.config regarding url name and time span
		/// </summary>
		public void GetConfigDetails()
		{
			try
			{
				Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
				TargetDetails tr = (TargetDetails)config.GetSection("targetUrl");

				for (int i = 0; i <= tr.details.Count - 1; i++)
				{
					string[] timerDetails = tr.details[i].timeSpan.ToString().Split(':');
					if (timerDetails.Length == 3)
						InitiateTimer(Convert.ToInt32(timerDetails[0]), Convert.ToInt32(timerDetails[1]), Convert.ToInt32(timerDetails[2]), tr.details[i].urlName);
				}
			}
			catch (Exception ex)
			{
				LogInfo(string.Format("invalid entry in config file :{0} exception with message {1} and {2}", ex.ToString(), ex.Message, ex.StackTrace.ToString()), true);
			}
		}

		/// <summary>
		/// configure timer and start it 
		/// </summary>
		/// <param name="hours"></param>
		/// <param name="mins"></param>
		/// <param name="secs"></param>
		/// <param name="Url"></param>
		private void InitiateTimer(int hours, int mins, int secs, string url)
		{
			SendRequest(url);
			TimeSpan tSpan = new TimeSpan(hours, mins, secs);
			Timer t = new Timer(tSpan.TotalMilliseconds);
			
			t.AutoReset = true;
			t.Start();
			t.Elapsed += delegate(object sender, ElapsedEventArgs e)
			{
				t_Elapsed(url);
			};
		}

		void t_Elapsed(string url)
		{
			SendRequest(url);
		}

		/// <summary>
		/// send web request to url and catch response
		/// </summary>
		/// <param name="url"></param>
		private void SendRequest(string url)
		{
			try
			{
				HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url));
				try
				{
					WebResponse res = req.GetResponse();
					HttpWebResponse httpRes = (HttpWebResponse)res;

					LogInfo(string.Format("Response received from url {0} has status code of {1} and status description as {2}", url, ((int)httpRes.StatusCode).ToString(), httpRes.StatusDescription), false);					
				}
				catch (WebException ex)
				{
					using (WebResponse r = ex.Response)
					{
						HttpWebResponse hwResp = (HttpWebResponse)r;
						string code = (hwResp != null) ? string.Format("URL ({0}) has error status code of {1} : {2}", url, ((int)hwResp.StatusCode).ToString(), hwResp.StatusDescription) : string.Format("Invalid Request for {0}", url);
						LogInfo(code, true);
					}
				}
			}
			catch (WebException e)
			{
				LogInfo(e.Message, true);
			}
		}

		/// <summary>
		/// log the information in application event log 
		/// </summary>
		/// <param name="message"></param>
		/// <param name="IsError"></param>
		private void LogInfo(string message, bool IsError)
		{
			if (!EventLog.SourceExists(sourceName))
			{
				EventLog.CreateEventSource(sourceName, logName);
			}		
			
			if (IsError)
				EventLog.WriteEntry(sourceName, string.Format("Exception reported at [{1}] : {0}", message, DateTime.Now), EventLogEntryType.Error);
			else
				EventLog.WriteEntry(sourceName, string.Format("Information reported at [{1}] : {0}", message, DateTime.Now), EventLogEntryType.Information);
		}
	}
}
